package com.norteksoft.struts.web.ec;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.Preferences;
import org.extremecomponents.table.core.PreferencesConstants;
import org.extremecomponents.table.core.TableConstants;
import org.extremecomponents.table.core.TableModelUtils;
import org.extremecomponents.table.core.TableProperties;
import org.extremecomponents.table.limit.Filter;
import org.extremecomponents.table.limit.FilterSet;
import org.extremecomponents.table.limit.Limit;
import org.extremecomponents.table.limit.LimitFactory;
import org.extremecomponents.table.limit.Sort;
import org.extremecomponents.table.limit.TableLimit;
import org.extremecomponents.table.limit.TableLimitFactory;

public class PaginationUtil {
	private static Log log = LogFactory.getLog(PaginationUtil.class);
	
	public static ECInfomationBean initializeEC(String tableId,HttpServletRequest request){
		/** 
		 * 得到系统默认的页面显示大小
		 */
		Context context = new HttpServletRequestContext(request);
		LimitFactory limitFactory = new TableLimitFactory(context, tableId);
	    Limit limit = new TableLimit(limitFactory);
	    Preferences preferences = new TableProperties();
	    preferences.init(null, TableModelUtils.getPreferencesLocation(context));
	    String crdStr = tableId + "_" + TableConstants.CURRENT_ROWS_DISPLAYED;
	    /**
	     *注意：此处取值时，如果后台配置文件里有配置，就从里面取，反之取15
	     */
	    int defaultRowsDisplayed = Integer.parseInt(preferences.getPreference(
	    		PreferencesConstants.TABLE_ROWS_DISPLAYED));
        if (request.getParameter(crdStr) != null) {
           defaultRowsDisplayed = Integer.parseInt(request .getParameter(crdStr));
        }
        
        //limit.setRowAttributes(totalRows, defaultRowsDisplayed);
        ECInfomationBean ecInfo=new ECInfomationBean(limit, defaultRowsDisplayed);
        return ecInfo;
	}
	
	public static ECInfomationBean initializeEC(HttpServletRequest request){
		//默认tableID为"ec"
		return initializeEC("ec",request);
	}
	
	public static Limit getLimit(String tableId,HttpServletRequest request){
		Context context = new HttpServletRequestContext(request);
	    LimitFactory limitFactory = new TableLimitFactory(context, tableId);
	    Limit limit = new TableLimit(limitFactory);
	    return limit;
	}
	public static int doOther(String tableId,int totalRows,Limit limit,HttpServletRequest request){
		/** 
		 * 得到系统默认的页面显示大小
		 */
		Context context = new HttpServletRequestContext(request);
	    Preferences preferences = new TableProperties();
	    preferences.init(null, TableModelUtils.getPreferencesLocation(context));
	    String crdStr = tableId + "_" + TableConstants.CURRENT_ROWS_DISPLAYED;
	    /**
	     *注意：此处取值时，如果后台配置文件里有配置，就从里面取，反之取15
	     */
	    int defaultRowsDisplayed = Integer.parseInt(preferences.getPreference(
	    		PreferencesConstants.TABLE_ROWS_DISPLAYED));
        if (request.getParameter(crdStr) != null) {
           defaultRowsDisplayed = Integer.parseInt(request .getParameter(crdStr));
        }
        limit.setRowAttributes(totalRows, defaultRowsDisplayed);
        /** 
         * 将totalRow信息传送回JSP以便eXtremeTable知道如何显示这些信息
         */
        request.setAttribute("totalRows", new Integer(totalRows));
        return defaultRowsDisplayed;
	}
	
	public static String filterQuery(FilterSet filterSet, String query,Map createMap) {
	       if (!filterSet.isFiltered() || filterSet.isCleared()) {
	    	   if(!filterSet.isFiltered())
	    		   log.debug("***********!filterSet.isFiltered()");
	    	   else
	    		   log.debug("***********filterSet.isCleared()");
	           return query;
	       }
	       Filter filters[] = filterSet.getFilters();
	       for (int i = 0; i < filters.length; i++) {
	           Filter filter = filters[i];
	           String property = filter.getProperty();
	           String value = filter.getValue();
	           String type = (String)createMap.get(property);
	           log.debug(property+"的类型为:"+type);
	           query = filterQuery(query, property, value,type);
	       }
	       return query;
	}
	private static String filterQuery(String query, String property, String value,String type) {
	       StringBuffer result = new StringBuffer(query);
	       if (query.indexOf("WHERE") == -1) {
	    	   result.append(" WHERE 1 = 1 "); // stub WHERE clause so can just
	           // append AND clause
	       }
	       if(type.equals("text"))
	    	   result.append(" AND " + property + " like '%" + value + "%'");
	       else 
	    	   result.append(" AND " + property + " = '" + value + "'");
	       return result.toString();
	}
	public static String sortQuery(Sort sort, String query) {
	       if (!sort.isSorted()) {
	    	   log.debug("!sort.isSorted()******************");
	           return query;
	       } 
	       String property = sort.getProperty();
	       String sortOrder = sort.getSortOrder();
	       return sortQuery(query, property, sortOrder);
	}
	private static String sortQuery(String query, String property, String sortOrder) {
	    StringBuffer result = new StringBuffer(query + " ORDER BY ");
	    result.append(property + " " + sortOrder);
	    return result.toString();
	}
	
	public static int getTotalPages(int totalRows,int rowsDisplayed){
		int a;
		if(totalRows%rowsDisplayed==0)
			a = totalRows/rowsDisplayed;
		else
			a = totalRows/rowsDisplayed+1;
		return a;
	}
}
